import getLodop from './LodopFuncs.js'
import {IPage, QYComponent} from "../domains/qy-component.ts";
import {createComHtml} from "../components/tool.ts";

export default {preview}

let strCompanyName = ''
let strLicense = ''
let strLicenseA = ''
let strLicenseB = ''

/**
 * 打印预览功能
 * @param {*Object} template 打印模板
 * @param {*Array} data 打印数据
 */
async function preview(template: IPage, data) {
    let LODOP = _createLodop(template.title, template.width, template.height, template.pageWidth, template.pageHeight)
    let tempItems = [...template.tempItems]
    if (data.length > 1) {
        // 打印多份
        for (let i = 0; i < data.length; i++) {
            LODOP.NewPageA()
            for (let index = 0; index < tempItems.length; index++) {
                await _addPrintItem(LODOP, tempItems[index], data[i])
            }
        }
    } else {
        // 单份
        for (let index = 0; index < tempItems.length; index++) {
            await _addPrintItem(LODOP, tempItems[index], data[0])
        }
    }
    LODOP.PREVIEW()
}

async function _addPrintItem(LODOP:any, printItem: QYComponent, data:any) {
    await createComHtml(printItem, data, LODOP);
    LODOP.SET_PRINT_STYLEA(0, "ItemType", printItem.itemType);
}


function _createLodop(pageName, width, height, pageWidth = 0, pageHeight = 0, top = 0, left = 0) {
    let LODOP = getLodop()
    // 设置软件产品注册信息
    LODOP.SET_LICENSES(strCompanyName, strLicense, strLicenseA, strLicenseB)
    LODOP.PRINT_INITA(top, left, width, height, pageName)
    LODOP.SET_PRINT_PAGESIZE(1, pageWidth ? pageWidth + 'mm' : 0, pageHeight ? pageHeight + 'mm' : 0, '')
    return LODOP
}
